package com.wjh.anyview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wjh.anyview.auth.dto.SignResult;
import com.wjh.anyview.auth.util.SecurityUtil;
import com.wjh.anyview.dao.*;
import com.wjh.anyview.entity.bo.userServiceBo.LoginBo;
import com.wjh.anyview.entity.bo.userServiceBo.UserLoginBo;
import com.wjh.anyview.entity.dto.CommonResult;
import com.wjh.anyview.entity.po.Clazz;
import com.wjh.anyview.entity.po.Institution;
import com.wjh.anyview.entity.po.LegalUser;
import com.wjh.anyview.entity.po.User;
import com.wjh.anyview.entity.vo.userControllerVo.InvigilatorVo;
import com.wjh.anyview.entity.vo.userControllerVo.UserVo;
import com.wjh.anyview.service.RbacService;
import com.wjh.anyview.service.UserService;
import com.wjh.anyview.service.constant.StringConstant;
import com.wjh.anyview.util.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wjh
 * @date 2021/10/9 19:04
 * @Package com.wjh.anyview.service.impl
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private SecurityUtil securityUtil;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private InstitutionMapper institutionMapper;

    @Resource
    private ClazzMapper clazzMapper;

    @Resource
    private LegalUserMapper legalUserMapper;

    @Resource
    private RbacService rbacService;

    @Override
    public CommonResult<UserLoginBo> login(LoginBo loginBo) {
        UserLoginBo userLoginBo = new UserLoginBo();

        //根据学号来查询User对象
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("num", loginBo.getNum());
        User user = userMapper.selectOne(wrapper);

        //账号未注册
        if (user == null) {
            return CommonResult.operateFailWithMessage("登录失败，该学工号未在本平台注册！");
        }

        //密码错误
        if (!user.getPassword().equals(Md5Util.getMD5String(loginBo.getPassword()))) {
            return CommonResult.operateFailWithMessage("登录失败，密码错误！");
        }

        //返回的userVo
        UserVo userVo = new UserVo();
        //返回用户id
        userVo.setId(user.getId());
        //返回学工号
        userVo.setNum(user.getNum());
        //返回在线状态
        userVo.setStatus(user.getStatus());

        userVo.setInstitutionId(user.getInstitutionId());
        if (user.getInstitutionId() != 0) {
            //根据隶属机构id查询机构对象
            QueryWrapper<Institution> institutionQueryWrapper = new QueryWrapper<>();
            institutionQueryWrapper.eq("id", user.getInstitutionId());
            Institution institution = institutionMapper.selectOne(institutionQueryWrapper);
            String institutionName = institution.getSchool() + " " + institution.getCollege();
            //返回机构名
            userVo.setInstitution(institutionName);
        } else {
            userVo.setInstitution(StringConstant.NO_INSTITUTION);
        }

        //返回班级id
        userVo.setClazzId(user.getClazzId());
        if (user.getClazzId() != 0) {
            if (user.getClazzId() == -1) {
                userVo.setClazz(StringConstant.NO_CLAZZ);
            } else {
                //根据所属班级id查询班级对象
                QueryWrapper<Clazz> clazzQueryWrapper = new QueryWrapper<>();
                clazzQueryWrapper.eq("id", user.getClazzId());
                Clazz clazz = clazzMapper.selectOne(clazzQueryWrapper);
                //返回班级名
                userVo.setClazz(clazz.getClazzName());
            }
        } else {
            userVo.setClazz(StringConstant.NO_CLAZZ);
        }

        userLoginBo.setUserVo(userVo);
        //查询角色
        List<String> roleList = roleMapper.listRoleByUserId(user.getId());
        if (!roleList.contains(loginBo.getLoginPosition())) {
            return CommonResult.operateFailWithMessage("账号或密码错误！");
        }
        //查询用户权限
        List<String> permissionList = permissionMapper.listPermissionsByUserId(user.getId());
        userLoginBo.setPermissionList(permissionList);

        //设置token
        SignResult signResult = securityUtil.login(user.getId().toString(), permissionList, user);
        if (signResult.isSuccess()) {
            //签发token
            userLoginBo.setToken(signResult.getToken());
            //token过期时间
            userLoginBo.setExpireAt(signResult.getExpireAt());
            //该用户具有的权限
            userLoginBo.setPermissionList(permissionList);
            //该用户具有的角色
            userLoginBo.setRoleList(roleMapper.listRoleByUserId(user.getId()));
            return CommonResult.operateSuccess(userLoginBo);
        }

        return CommonResult.operateFailWithMessage(StringConstant.SYSTEM_BUSY);
    }

    @Override
    @Transactional
    public CommonResult<?> saveStudent(User user) {
        if (!registerJudge(user.getNum())) {
            return CommonResult.operateFailWithMessage("该学号已注册或不合法！");
        }
        //md5加密密码
        user.setPassword(Md5Util.getMD5String(user.getPassword()));
        //插入数据库
        userMapper.insert(user);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("num", user.getNum());
        User result = userMapper.selectOne(wrapper);
        //设置为user
        rbacService.setUserRole(result.getId());
        //设置为student
        rbacService.setStudentRole(result.getId());
        return CommonResult.operateSuccess();
    }

    @Override
    public boolean registerJudge(String num) {
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq("num", num);
        //查重
        if (userMapper.selectOne(userWrapper) != null) {
            return false;
        }
        QueryWrapper<LegalUser> legalUserWrapper = new QueryWrapper<>();
        legalUserWrapper.eq("legal_num", num);
        //查询是否合法
        return legalUserMapper.selectOne(legalUserWrapper) != null;
    }

    @Override
    public CommonResult<Byte> getGradeByNum(String num) {
        QueryWrapper<LegalUser> wrapper = new QueryWrapper<>();
        wrapper.eq("legal_num", num);
        LegalUser legalUser = legalUserMapper.selectOne(wrapper);
        return CommonResult.operateSuccess(legalUser.getGrade());
    }

    @Override
    public CommonResult<List<InvigilatorVo>> listInvigilatorByInstitutionId(Long institutionId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("institution_id", institutionId);
        //教师的clazzId为-1
        wrapper.eq("clazz_id", -1);
        List<User> userList = userMapper.selectList(wrapper);
        List<InvigilatorVo> list = new ArrayList<>();
        userList.forEach(user -> {
            InvigilatorVo invigilatorVo = new InvigilatorVo();
            invigilatorVo.setId(user.getId());
            invigilatorVo.setName(user.getName());
            invigilatorVo.setNum(user.getNum());
            list.add(invigilatorVo);
        });
        return CommonResult.operateSuccess(list);
    }

}
